package com.grj.service.common.controller;

import com.grj.service.common.config.MinioTemplate;
import io.minio.messages.Bucket;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 14505
 */
@RestController
@RequestMapping("/minio")
@RequiredArgsConstructor
public class MinioController {
    private final MinioTemplate minioTemplate;

    //创建新的桶
    @GetMapping("createBucket")
    public Object createBucket(String bucketName){
        return minioTemplate.createBucket(bucketName);
    }

    //获取对应桶信息
    @GetMapping("getList")
    public Object getList(String bucketName){
        Bucket bucket = minioTemplate.getBucket(bucketName).get();
        Map<String,Object> map = new HashMap<>();
        map.put("name",bucket.name());
        map.put("createDate",bucket.creationDate());
        return map;
    }

    //获取所有桶信息
    @GetMapping("getAll")
    public Object getAll(){
        List<Map> list = new ArrayList<>();
        List<Bucket> buckets = minioTemplate.getAllBuckets();
        buckets.stream().forEach(item -> {
            Map<String,Object> map = new HashMap<>();
            map.put("name",item.name());
            map.put("createDate",item.creationDate());
            list.add(map);
        });
        return list;
    }

    /**上传文件到对应桶里，如果你想放入指定文件夹，传入文件名前面带上文件夹名称及路径，比如 test文件夹就- test/文件名，依次类推*/
    @PostMapping("uploadFile")
    public Object uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
        /**文件夹属性，可加载文件前方*/
        return minioTemplate.putObject("test","uu/" + file.getOriginalFilename(),file);
    }

    /**获取图片信息，二进制数据转换为图片呈现*/
    @GetMapping(value = "getFile", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] getFile(@RequestParam("bucketName") String bucketName
            ,@RequestParam("objectName") String objectName) throws IOException {
        InputStream stream = minioTemplate.getObject(bucketName, objectName);
        return null;
    }

    /**获取图片分享链接，expires为过期时间，可为小于等于7*/
    @GetMapping(value = "getObjectUrl")
    public String getObjectUrl(@RequestParam("bucketName") String bucketName
            ,@RequestParam("objectName") String objectName) throws IOException {
        return minioTemplate.getObjectUrl(bucketName, objectName, 1);
    }

}
